package com.ph.realm;

import com.ph.config.UUIDToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class UUIDRealm extends AuthorizingRealm {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UUIDToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UUIDToken token1 = (UUIDToken) token;
        if (!StringUtils.hasText(token1.getUuid())){
            throw new AuthenticationException("token不能为空");
        }
        Integer id = (Integer) redisTemplate.opsForValue().get(token1.getUuid());
        if (id == null){
            throw new AuthenticationException("token已过期");
        }
        return new SimpleAuthenticationInfo(id,token1.getUuid(),getName());
    }
}
